package com.cmy.framework_base.basics

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.cmy.framework_base.common.BaseStateView
import com.cmy.framework_base.common.UiState
import com.cmy.framework_base.common.loading.LoadDialogView
import com.cmy.framework_base.common.loadsir.EmptyCallback
import com.cmy.framework_base.common.loadsir.ErrorCallback
import com.cmy.framework_base.common.loadsir.LoadingCallback
import com.cmy.framework_utils.log.KLog
import com.cmy.framework_utils.toast.toast
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.permissionx.guolindev.PermissionX
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch

/**
 * @name:
 *  BasicsFragment
 * @package:
 *  com.cmy.framework_base.basics
 * @date:
 *  2023/2/1615:00
 * @author
 *    cmy
 * @description
 *  所有Fragment的基础类，实现各类基础数据的处理
 */
abstract class BasicsFragment : Fragment() , BaseStateView {

    companion object {
        private const val STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN"
    }

    protected val mHandler = Handler(Looper.getMainLooper())

    /**
     * 根目录布局
     */
    private var mRootView: FrameLayout? = null


    /**
     * 内容页布局
     */
    private var mContentView: View? = null

    /**
     * 第一次加载
     */
    private var isFirstLoad = true

    /**
     * 异步加载View
     */
    private var isAsyncView = false


    /**
     * 数据存储
     */
    protected var savedInstanceState: Bundle? = null

    /**
     * 上下文环境参数
     */
    protected var mContext: Context? = null

    /**
     * 状态管理
     */
    private var mLoadService: LoadService<Any>? = null



    /**
     * 页面加载状态显示
     */
    private var mLoadDialogView: LoadDialogView? = null

    //-------------------------------需要实现的抽象方法--------------------------------------
    /**
     * 返回视图
     */
    protected abstract fun getContentView(): View?

    /**
     * 视图初始化
     */
    protected abstract fun initView(bundle: Bundle?)

    /**
     * 数据初始化
     */
    protected abstract fun initData()


    //--------------------------可重写实现对应UI逻辑方法------------------------


    /**
     * 失败重试,重新加载事件
     */
    protected open fun onReloadClick() {}


    /**
     * 提供子类方法 在设置布局之前
     */
    protected open fun setWindowConfigure() {}

    /**
     * 总是需要重新加载
     */
    protected open fun alwaysNeedReload() {}


    /**
     * 再次可见时，是否重新请求数据，默认为true
     */
    protected open fun isNeedReload() = true

    /**
     * fragment是否懒加载  默认 false
     *
     * @return
     */
    protected open fun isAsyncLoadView() = false


    /**
     * 懒加载
     */
    protected open fun onCreateAsyncView(inflater: LayoutInflater, container: ViewGroup?) {}


    protected open fun  doBundle(bundle: Bundle){}


    //------------------------------继承方法的实现-------------------------

    override fun showContent() {
        mLoadService?.let {
            mHandler.post { it.showSuccess() }
        }
    }

    override fun showLoading() {
        mLoadService?.let {
            mHandler.post { it.showCallback(LoadingCallback::class.java) }
        }
    }

    override fun showEmpty() {
        mLoadService?.let {
            mHandler.post { it.showCallback(EmptyCallback::class.java) }
        }
    }

    override fun showFailure(message: String?) {
        mLoadService?.let {
            mHandler.post { it.showCallback(ErrorCallback::class.java) }
            mContext?.let {
                message?.toast(it)
            }

        }
    }


    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putBoolean(STATE_SAVE_IS_HIDDEN, isHidden)
    }



    //-------------------------------生命周期数据绑定--------------------------


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (savedInstanceState != null) {
            val isSupportHidden =
                savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN)
            childFragmentManager.let {
                val ft = it.beginTransaction()
                if (isSupportHidden) {
                    ft.hide(this)
                } else {
                    ft.show(this)
                }
                ft.commitAllowingStateLoss()
            }
        }

        arguments?.let {
            doBundle(it)
        }
        setWindowConfigure()
        if (isAsyncLoadView()) {
            initRootView()
            onCreateAsyncView(inflater, container)
        } else {
            mContentView = getContentView()
        }


        return mRootView ?: mContentView
    }



    override fun onAttach(context: Context) {
        super.onAttach(context)
        this.mContext = context
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.savedInstanceState = savedInstanceState
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(arguments)
    }



    override fun onResume() {
        super.onResume()
        onResumeLoad()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        clearDisposable()
    }


    //-----------------------------自定义已实现的方法----------------------------


    private fun initRootView() {
        mRootView = FrameLayout(requireActivity().applicationContext)
        mRootView?.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
    }

    /**
     * 是否在可见的时候加载
     */
    private fun onResumeLoad() {
        alwaysNeedReload()
        if (!isAsyncLoadView()) {
            if (isFirstLoad) {
                initData()
                isFirstLoad = false
            } else {
                if (isNeedReload()) {
                    initData()
                }
            }
        } else {
            if (isAsyncView) {
                if (isNeedReload()) {
                    initData()
                }
            }
        }
    }


    /**
     * 请求权限
     */
    fun requestPermissions(vararg permissions: String, block: () -> Unit) {
        requestPermissions(listOf(*permissions), block)
    }

    private fun requestPermissions(permissions: List<String>, block: () -> Unit) {
        PermissionX.init(this)
            .permissions(permissions)
            .request { allGranted, _, deniedList ->
                if (allGranted) {
                    block()
                } else {
                    mContext?.let {
                        "您拒绝了如下权限：$deniedList".toast(it)
                    }
                }
            }
    }




    /**
     * 取消所有订阅，防止内存泄漏
     */
    private fun clearDisposable() {
        if (mLoadDialogView != null){
            mLoadDialogView!!.dismissLoadView()
            mLoadDialogView = null
        }

    }



    /**
     * 显示加载View
     */
    private fun showLoadView() {
        activity?.let {
            mLoadDialogView?.showLoadView()
        }
    }

    /**
     * 关闭加载View
     */
    private fun dismissLoadView() {
        activity?.let {
            mLoadDialogView?.dismissLoadView()
        }
    }


    /**
     * 延时关闭加载View
     */
    fun dismissLoadView(delay: Long) {
        activity?.let {
            mLoadDialogView?.dismissLoadView(delay)
        }
    }

    /**
     * 监听加载的UI用户界面状态
     */
    @SuppressLint("UnsafeRepeatOnLifecycleDetector")
    fun refreshUiState(uiState: MutableStateFlow<UiState>) {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                uiState.collect {
                    KLog.e("-------lifecycleScope.UiState = $it")
                    when (it) {
                        UiState.Loading -> showLoadView()
                        UiState.LoadEnd -> dismissLoadView()
                        UiState.LoadError -> dismissLoadView()
                        UiState.LoadComplete -> dismissLoadView()
                        else -> dismissLoadView()
                    }
                }
            }
        }
    }


    /**
     * 注册LoadSir
     *
     * @param view 替换视图
     */
    fun registerLoadSir(view: View) {
        mLoadService = LoadSir.getDefault().register(view) { onReloadClick() }
    }


    /**
     * 注册加载弹窗
     */
    fun registerLoadDialogView(loadDialogView: LoadDialogView){
        mLoadDialogView = loadDialogView
    }


    //----------------------------
    /**
     * 跳转页面
     *
     * @param clz    所跳转的目的Activity类
     * @param bundle 跳转所携带的信息
     */
   protected inline fun <reified T : Activity> startActivity(clz: T, bundle: Bundle? = null) {
        val intent = Intent(requireActivity(), clz::class.java)
        if (bundle != null) {
            intent.putExtras(bundle)
        }
        startActivity(intent)
    }
}